package com.whsxt.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.whsxt.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-10 16:10
 * @Description: jwt的校验
 */
@Configuration
public class JwtCheckFilter implements GlobalFilter, Ordered {


    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 1、判断是否是登录，如果是登录就直接放行
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //拿到request URL
        String path = exchange.getRequest().getURI().getPath();
        if (GatewayConstant.ALLOW_URL.contains(path)) {
            //放行
            return chain.filter(exchange);
        }

        //需要检查头部的token
        List<String> tokenList = exchange.getRequest().getHeaders().get(GatewayConstant.AUTHORIZATION);
        if (!CollectionUtils.isEmpty(tokenList)) {
            String token = tokenList.get(0);
            if (!StringUtils.isEmpty(token)) {
                //截取token
                String jwt = token.replaceAll("bearer ", "");
                if (!StringUtils.isEmpty(jwt)) {
                    //和redis做匹配
                    Boolean hasKey = redisTemplate.hasKey(GatewayConstant.JWT_PREFIX + jwt);
                    if (hasKey) {
                        //放行
                        return chain.filter(exchange);
                    }
                }
            }
        }

        //需要拦截，返回401，前端返回登录页面
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("content-type", "application/json;charset=utf-8");
        Map<String, Object> map = new HashMap<>();
        map.put("code", 401);
        map.put("msg", "未授权");
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];

        try {
            bytes = objectMapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer wrap = dataBufferFactory.wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
